package com.hskn.hss.module.tlcar.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.core.annotation.SysLog;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.enums.BusinessType;
import com.hskn.hss.core.utils.file.FileTypeUtils;
import com.hskn.hss.core.utils.poi.ExcelUtil;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.entity.TreeEntity;
import com.hskn.hss.exception.ExcelReaderDataException;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.common.ienum.ExcelTypeEnum;
import com.hskn.hss.module.common.to.ExcelReaderTO;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.storageDetail.mapper.TlStorageDetailMapper;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.mapper.TlCarMapper;
import com.hskn.hss.module.tlcar.service.ITlCarService;
import com.hskn.hss.module.tlcar.to.TICarExportTo;
import com.hskn.hss.module.tlcar.to.TlCarTo;
import com.hskn.hss.module.tlcar.vo.TlCarExcelOutVO;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.mapper.TlCarTypeMapper;
import com.hskn.hss.module.tlopetation.entity.TlOperation;
import com.hskn.hss.module.tlopetation.mapper.TlOperationMapper;
import com.hskn.hss.utils.GroupingByUtils;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-17
 */
@Api(tags = {"-tl_car"}, description = "车辆档案")
@Slf4j
@RestController
@RequestMapping("/hss/tlcar")
public class TlCarController {

    @Resource
    ITlCarService tlCarService;
    @Resource
    TlCarMapper tlCarMapper;
    @Resource
    TlCarTypeMapper tlCarTypeMapper;
    @Resource
    TlOperationMapper tlOperationMapper;
    @Autowired
    private ISysDepartService departService;

    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_car", bean = TlCar.class, beanMapper = TlCarMapper.class, names = "carnumber")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public AjaxResult<Object> insert(@RequestBody @Validated TlCar tlCar, HttpServletRequest request) {
        try {
            QueryWrapper<TlCar> tlCarQueryWrapper = new QueryWrapper<>();
            tlCarQueryWrapper.lambda().eq(TlCar::getCarnumber, tlCar.getCarnumber());
            List<TlCar> carList = tlCarMapper.selectList(tlCarQueryWrapper);
            if (carList.isEmpty()) {
                tlCarService.insert(tlCar);
                return AjaxResult.success(tlCar);
            } else {
                return AjaxResult.fail("该名称已存在，请重新输入");
            }


        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.UPDATE, tableName = "tl_car", idKey = "id", bean = TlCar.class, beanMapper = TlCarMapper.class, names = "carnumber")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public AjaxResult<Object> update(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            return tlCarService.update(params);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.UPDATE, tableName = "tl_car", idKey = "ids", bean = TlCar.class, beanMapper = TlCarMapper.class, names = "carnumber")
    @ApiOperation(value = "批量更新接口", notes = "批量更新")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlCar.class)
    })
    @RequestMapping(value = "updatebyids", method = RequestMethod.POST)
    public AjaxResult<Object> updatebyids(@RequestBody @Validated TlCar tlCar, HttpServletRequest request) {
        try {
            return tlCarService.updatebyids(tlCar);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.DELETE, tableName = "tl_car", idKey = "id", bean = TlCar.class, beanMapper = TlCarMapper.class, names = "carnumber")
    @RequestMapping(value = "deletebyid", method = RequestMethod.POST)
    public AjaxResult<Object> deletebyid(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        try {
            return tlCarService.deletebyid(params);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("删除失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.DELETE, tableName = "tl_car", idKey = "ids", bean = TlCar.class, beanMapper = TlCarMapper.class, names = "carnumber")
    @ApiOperation(value = "批量删除接口", notes = "批量删除")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlCar.class)
    })
    @RequestMapping(value = "deletebatchbyid", method = RequestMethod.POST)
    public AjaxResult<Object> deletebatchbyid(@RequestBody @Validated TlCar tlCar) {

        try {
            return tlCarService.deletebatchbyid(tlCar);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("删除失败，请稍后再试");
        }
    }

    @RequestMapping(value = "getSelectList", method = RequestMethod.POST)
    public AjaxResult<Object> getSelectList(HttpServletRequest request) {
        return AjaxResult.success(tlCarService.getSelectList());
    }

    @RequestMapping(value = "getDetail", method = RequestMethod.POST)
    public AjaxResult<Object> getDetail(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        TlCar tlCar = null;
        try {
            tlCar = tlCarService.getDetail(params);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }
        return AjaxResult.success(tlCar);

    }

    @RequestMapping(value = "getList", method = RequestMethod.POST)
    public AjaxResult<Object> getList(@RequestBody @Validated TlCarTo tlCarTo) {
        try {
            BaseEntity entity = new BaseEntity();
            return AjaxResult.success(tlCarService.getList(entity, tlCarTo));
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }
    }

    @RequestMapping(value = "tree", method = RequestMethod.POST)
    public AjaxResult<Object> tree(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        try {
                List<TreeEntity> carTree = tlCarService.getCarTree(params);
                return AjaxResult.success(carTree);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("查询失败，请稍后再试");
        }
    }

    @RequestMapping(value = "cartree", method = RequestMethod.POST)
    public AjaxResult<Object> carTree(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        try {
            List<TreeEntity> carTree = tlCarService.getCarTree2(params);
            return AjaxResult.success(carTree);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("查询失败，请稍后再试");
        }
    }

    /**
     * 获取列表
     *
     * @param request
     * @return
     */
//    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_car", bean = TlCar.class, beanMapper = TlCarMapper.class, names = "carnumber")
    @ApiOperation(value = "车辆档案导入接口", notes = "车辆档案导入")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @PostMapping("excelReader")
    public AjaxResult excelReader(HttpServletRequest request, @Validated ExcelReaderTO excelReaderTo) {
        try {
            MultipartFile file = excelReaderTo.getFiles();
            if (Arrays.stream(ExcelTypeEnum.values()).noneMatch(s -> s.getName().equals(FileTypeUtils.getFileType(file.getOriginalFilename().toLowerCase())))) {
                return AjaxResult.fail("导入文件格式错误");
            }

            InputStream inputStream = new BufferedInputStream(file.getInputStream());
            ExcelUtil<TlCar> util = new ExcelUtil<TlCar>(TlCar.class);

            List<TlCar> tlCarList = util.importExcel(inputStream);
            if (tlCarList.isEmpty()) {
                return AjaxResult.fail("导入内容为空");
            }
            tlCarService.excelReader(tlCarList);

//            //车牌号为空判断
//            String message = " ";
//            for(TlCar tl : tlCarList){
//                if(StringUtils.isEmpty(tl.getCardeptid())){
//                    message +="车牌号不能为空;##";
//                }
//            }
//            //导入重复判断
//            List<TlCar> tlCars = tlCarMapper.selectList(new QueryWrapper<>());
//            Map<String,List<TlCar>> map = tlCars.stream().collect(Collectors.groupingBy(TlCar::getCarnumber));
//            //导入文件内部重复判断
//            List<String> code = tlCars.stream().map(TlCar::getCarnumber).collect(Collectors.toList());
//            if(AttributeUtils.RepeatedCheck(code) == false){
//                message +="导入文件中车牌号有重复;##";
//            }
//            for(TlCar tl : tlCarList) {
//                if (CollectionUtils.isNotEmpty(map.get(tl.getCarnumber()))) {
//                    message += "档案中已存在车牌号:" + tl.getCarnumber() + ";##";
//                }
//            }
//            if(StringUtils.isNotEmpty(message)){
//                return AjaxResult.fail("您导入的数据:##"+message);
//            }
//            //导入判断结束
            if (tlCarService.saveBatch(tlCarList)) {
                return AjaxResult.success();
            } else {
                return AjaxResult.fail("导入失败");
            }
        } catch (ExcelReaderDataException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception exception) {
            exception.printStackTrace();
            return AjaxResult.fail();
        }
    }

    //TODO 要有一个模板接口
    @ApiOperation(value = "车辆档案导出接口", notes = "车辆档案导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @PostMapping("excelExport")
    public com.hskn.hss.core.domain.AjaxResult excelExport(HttpServletRequest request, @RequestBody TICarExportTo tiCarExportTo) {
        try {
            if(tiCarExportTo.getIds()!=null&&tiCarExportTo.getIds().isEmpty()){
                return com.hskn.hss.core.domain.AjaxResult.error("请选择至少一条数据导出");
            }
            QueryWrapper<TlCar> tlCarQueryWrapper = new QueryWrapper<>();
            QueryWrapper<TlCarType> tlCarTypeQueryWrapper = new QueryWrapper<>();
            QueryWrapper<TlOperation> tlOperationQueryWrapper = new QueryWrapper<>();

            if (StringUtils.isNotEmpty(tiCarExportTo.getCardeptid())) {
                tlCarQueryWrapper.lambda().eq(TlCar::getCardeptid, tiCarExportTo.getCardeptid());
            }
            if (StringUtils.isNotEmpty(tiCarExportTo.getCarnumber())) {
                tlCarQueryWrapper.lambda().eq(TlCar::getCarnumber, tiCarExportTo.getCarnumber());
            }
            if (StringUtils.isNotEmpty(tiCarExportTo.getCartypeid())) {
                tlCarQueryWrapper.lambda().eq(TlCar::getCartypeid, tiCarExportTo.getCartypeid());
            }
            if (StringUtils.isNotEmpty(tiCarExportTo.getCarattribution())) {
                tlCarQueryWrapper.lambda().eq(TlCar::getCarattribution, tiCarExportTo.getCarattribution());
            }
            if (StringUtils.isNotEmpty(tiCarExportTo.getStatus())) {
                tlCarQueryWrapper.lambda().eq(TlCar::getStatus, tiCarExportTo.getStatus());
            }
            if (StringUtils.isNotEmpty(tiCarExportTo.getCarcategory())) {
                tlCarQueryWrapper.lambda().eq(TlCar::getCarcategory, tiCarExportTo.getCarcategory());
            }
            if (StringUtils.isNotEmpty(tiCarExportTo.getCarcategoryitem())) {
                tlCarQueryWrapper.lambda().eq(TlCar::getCarcategoryitem, tiCarExportTo.getCarcategoryitem());
            }
            if (tiCarExportTo.getIds() != null && !tiCarExportTo.getIds().isEmpty()) {
                tlCarQueryWrapper.lambda().in(TlCar::getId, tiCarExportTo.getIds());
            }
            if (StringUtils.isNotEmpty(tiCarExportTo.getDrivemodel())) {
                tlCarQueryWrapper.lambda().eq(TlCar::getCarmodelid, tiCarExportTo.getDrivemodel());
            }
            List<TlCar> tlCarList = tlCarMapper.selectList(tlCarQueryWrapper);
            if (tlCarList.isEmpty()) {
                return com.hskn.hss.core.domain.AjaxResult.error("导出数据为空");
            }
            ExcelUtil<TlCarExcelOutVO> util = new ExcelUtil<TlCarExcelOutVO>(TlCarExcelOutVO.class);
            List<TlCarExcelOutVO> tlCarExcelOutVOList = JSONObject.parseArray(JSONObject.toJSONString(tlCarList), TlCarExcelOutVO.class);
            Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
            List<TlCarType> tlCarTypeList = tlCarTypeMapper.selectList(tlCarTypeQueryWrapper);
            Map<String, TlCarType> tlCarTypeMap = GroupingByUtils.getGroupingForMapEntity(tlCarTypeList, TlCarType::getId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
            List<TlOperation> tlOperationList = tlOperationMapper.selectList(tlOperationQueryWrapper);
            Map<String, TlOperation> tlOperationMap = GroupingByUtils.getGroupingForMapEntity(tlOperationList, TlOperation::getId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));

            for (TlCarExcelOutVO tlCarExcelOutVO : tlCarExcelOutVOList) {
                if (departMap.containsKey(tlCarExcelOutVO.getCardeptid())) {
                    tlCarExcelOutVO.setCardeptname(departMap.get(tlCarExcelOutVO.getCardeptid()).getDepartName());
                }
                if (tlCarTypeMap.containsKey(tlCarExcelOutVO.getCartypeid())) {
                    tlCarExcelOutVO.setCarTypeName(tlCarTypeMap.get(tlCarExcelOutVO.getCartypeid()).getTypename());
                }
                if (tlOperationMap.containsKey(tlCarExcelOutVO.getCarcategory())) {
                    tlCarExcelOutVO.setCarcategoryname(tlOperationMap.get(tlCarExcelOutVO.getCarcategory()).getOperationtype());
                }
            }
            return util.exportExcel(tlCarExcelOutVOList, "车辆档案");

        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }

    @ApiOperation(value = "车辆档案导出模板接口", notes = "车辆档案模板导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlCarExcelOutVO.class)
    })
    @PostMapping("excelExportTemplate")
    public com.hskn.hss.core.domain.AjaxResult excelExportTemplate(HttpServletRequest request) {
        try {
            //工具类实例化
            ExcelUtil<TlCar> util = new ExcelUtil<TlCar>(TlCar.class);
            //数据载体转换
            List<TlCar> tlCarExcelOutVOList = new ArrayList<>();
            //导出
            return util.exportExcel(tlCarExcelOutVOList, "车辆档案模板");
        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }
}

